#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: content.py
# Author: Tomás Vírseda
# License: GPL v3
# Description:  The content manager show the resources in several ways.

"""
"""
import os

import gobject
import gtk
import pango
import datetime

import webkit

from vazaarlib.namespaces import *
from vazaarlib.constants import GUI_DIR, IMAGES_DIR
from vazaarlib.ui.glade import Widgets
from vazaarlib.ui.sparql import SPARQLEditor
from vazaarlib.ui.starthere import StartHere
from vazaarlib.ui.widgets.webbrowser import WebBrowser
from vazaarlib.ui.widgets.sourceview import SourceView
from vazaarlib.ui.widgets.customview import IconView
from vazaarlib.ui.widgets.customview import ListView
from vazaarlib.ui.widgets.imageviewer import ImageViewer
from vazaarlib.ui.backup import BackupManager
from vazaarlib.ui.visor import Visor

class ContentManager:
    """ content manager """

    def __init__(self, gui):
        self.gui = gui
        self.graph = self.gui.get_graph()
        self.sparql = SPARQLEditor(self.gui)
        self.starthere = StartHere(self.gui)
        self.backup = BackupManager(self.gui)
        self.cont = 0
        # containers
        self.gui.frontend['content'] = self.gui.glade.widgets.get_widget("content")
        self.gui.frontend['views'] = self.gui.glade.widgets.get_widget("ntbViews")
        self.gui.frontend['notebook'] = self.gui.glade.widgets.get_widget("ntbContent")
        self.gui.frontend['starthere'] = self.gui.glade.widgets.get_widget("cntStartHere")

        # labels
        self.gui.frontend['label'] = self.gui.glade.widgets.get_widget("lblContent")

        # icons
        self.gui.frontend['image'] = self.gui.glade.widgets.get_widget("imgContent")

        self.gui.frontend['connections'] = {
            'ntbContent/switch-page' :    self.select_page,
        }

        #connect signals
        for wid_con, func in self.gui.frontend['connections'].iteritems():
            wid,con = wid_con.split('/')
            self.gui.glade[wid].connect(con,func)


    def __build_tab(self, id, name, widget, icon):
        label = gtk.Label()
        label.set_use_markup(True)
        label.set_markup("<i> %s </i>" % name)
        #label = gtk.Button(name)
        #label.set_relief(gtk.RELIEF_NONE)
        #label.connect('clicked', self.__open_page, self.gui.frontend['notebook'], widget)
        tab = gtk.HBox()
        micon = gtk.Button()
        #icon = icon.scale_simple(24, 24, gtk.gdk.INTERP_BILINEAR)
        micon.set_image(gtk.image_new_from_pixbuf(icon))
        micon.set_relief(gtk.RELIEF_NONE)
        micon.connect('clicked', self.__edit_resource, id, self.gui.frontend['notebook'], widget)
        close = gtk.Image()
        button = gtk.Button()
        close.set_from_file(IMAGES_DIR + '/gtk-close.png')
        button.set_image(close)
        button.set_relief(gtk.RELIEF_NONE)
        button.connect('clicked', self.__close_page, self.gui.frontend['notebook'], widget)
        tab.pack_start(micon, False, False)
        tab.pack_start(label, False, False)
        tab.pack_end(button, False, False)
        tab.show_all()

        return tab


    def __edit_resource(self, widget, id, notebook, ntbwidget):
        """ show the resource editor """
        self.gui.editor.update_id(id)
        #browser = widget
        page_num = notebook.page_num(ntbwidget)

        if page_num != -1:
            notebook.set_current_page(page_num)
            self.gui.editor.show_dialog()



    def __close_page(self, button, notebook, widget):
        """remove a notebook tab"""

        #browser = widget
        page_num = notebook.page_num(widget)

        if page_num != -1:
            notebook.remove_page(page_num)
            self.gui.editor.hide_dialog()


    def select_page(self, notebook, page, page_num, user=None):
        pass
        #if page_num == 0:
        #    self.gui.frontend['sh-ntboper'].hide_all()

    def show_start_here(self):
        self.gui.frontend['image'].set_from_stock(gtk.STOCK_HOME, gtk.ICON_SIZE_BUTTON)
        self.gui.frontend['label'].set_markup("<big><b> Start Here </b></big>")
        self.gui.frontend['notebook'].set_current_page(0)
        self.gui.frontend['views'].set_current_page(0)

    def show_browser(self):
        self.gui.frontend['image'].set_from_stock(gtk.STOCK_INDEX, gtk.ICON_SIZE_BUTTON)
        self.gui.frontend['label'].set_markup("<big><b> Browser </b></big>")
        self.gui.frontend['notebook'].set_current_page(0)
        self.gui.frontend['views'].set_current_page(1)

    def show_explorer(self):
        self.gui.frontend['image'].set_from_stock(gtk.STOCK_OPEN, gtk.ICON_SIZE_BUTTON)
        self.gui.frontend['label'].set_markup("<big><b> Explorer </b></big>")
        self.gui.frontend['notebook'].set_current_page(0)
        self.gui.frontend['views'].set_current_page(2)

    def show_queries(self):
        self.gui.frontend['image'].set_from_stock(gtk.STOCK_EXECUTE, gtk.ICON_SIZE_BUTTON)
        self.gui.frontend['label'].set_markup("<big><b> Queries </b></big>")
        self.gui.frontend['views'].set_current_page(3)
        self.gui.frontend['notebook'].set_current_page(0)

    def show_export(self):
        self.gui.frontend['image'].set_from_stock(gtk.STOCK_SAVE, gtk.ICON_SIZE_BUTTON)
        self.gui.frontend['label'].set_markup("<big><b> Export operations </b></big>")
        self.gui.frontend['notebook'].set_current_page(0)
        self.gui.frontend['views'].set_current_page(4)
        self.backup.show_export_operations()

    def show_import(self):
        self.gui.frontend['image'].set_from_stock(gtk.STOCK_SAVE, gtk.ICON_SIZE_BUTTON)
        self.gui.frontend['label'].set_markup("<big><b> Export operations </b></big>")
        self.gui.frontend['notebook'].set_current_page(0)
        self.gui.frontend['views'].set_current_page(4)
        self.backup.show_import_operations()

    def show_preferences(self):
        self.gui.frontend['image'].set_from_stock(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_BUTTON)
        self.gui.frontend['label'].set_markup("<big><b> Preferences </b></big>")
        self.gui.frontend['notebook'].set_current_page(0)
        self.gui.frontend['views'].set_current_page(5)

    def get_num_resources(self):
        return self.gui.frontend['notebook'].get_n_pages() - 1

    def display_resource(self, id):
        #   - browser: for web pages or images
        #   - text: for text files, source code, scripts, ...
        #   - sound: for music
        #   - video: for video
        #   - image: use browser but it will have its own widget
        #   - executable: any executable file
        #   - csv: text-based comma-separated files
        #   - directory: for a file explorer widget
        #   - collection: a widget with all resources belonging to that collection
        #   - unknow: open resource with an external program
        t1 = datetime.datetime.now()
        res = self.gui.app.vstore.get_virtual_resource(id)
        icon = self.gui.icons.get_icon_by_name(res.prop[RDF.type][0], 16, 16)

        try:
            widget_type = self.get_widget_type(res.prop[NIE['mimeType']][0])
        except:
            widget_type = 'collection'

        if widget_type == 'browser':        widget = WebBrowser(res.prop[NFO['fileUrl']][0])
        elif widget_type == 'text':         widget = SourceView(res.prop[NFO['fileUrl']][0])
        elif widget_type == 'image':        widget = WebBrowser(res.prop[NFO['fileUrl']][0])
        elif widget_type == 'sound':        widget = gtk.Label(res.prop[NIE['title']][0])
        elif widget_type == 'video':        widget = gtk.Label(res.prop[NIE['title']][0])
        elif widget_type == 'executable':   widget = gtk.Label(res.prop[NIE['title']][0])
        elif widget_type == 'csv':          widget = gtk.Label(res.prop[NIE['title']][0])
        elif widget_type == 'directory':    widget = gtk.Label(res.prop[NIE['title']][0])
        elif widget_type == 'collection':
            resources = self.gui.ask.resources_in_collection(id)
            columns = {}
            columns[0] = ('Id', gtk.CellRendererText())
            columns[1] = ('', gtk.CellRendererPixbuf())
            columns[2] = ('Collected', gtk.CellRendererText())
            columns[3] = ('Title', gtk.CellRendererText())
            widget = IconView(self.gui, columns, resources)#FIXME:
        else:
            widget = gtk.Label('Check this!')

        container = gtk.Frame()
        visor = Visor(self.gui, id, widget)
        container.add(visor)
        container.show_all()
        title = str(res.prop[NIE['title']][0])
        if len(title) > 30:
            name = title[0:30] + '...'
            #tab = self.__build_tab(name, container, icon)
        else:
            name = title

        tab = self.__build_tab(id, name, container, icon)

        page = self.gui.frontend['notebook'].insert_page(container, tab, -1)
        tab.set_data("page", page)
        #self.gui.frontend['notebook'].set_current_page(page)
        t2 = datetime.datetime.now()
        delta = t2 - t1
        pass #print "display resource took: %s" % delta
    def get_widget_type(self, mime):
        default = 'unknow'

        stype, dtype = mime.split('/')
        if stype == 'text' and dtype != 'html':
            default = stype
        elif stype == 'text' and dtype == 'html':
            default = 'browser'
        elif stype == 'application':
            default = 'unknow'
        elif stype == 'image':
            default = 'image'
        elif stype == 'video':
            default = 'unknow'

        return default

    def num_pages(self):
        return self.gui.frontend['notebook'].get_n_pages()
